package com.jinyang.baserouter

import android.app.Application
import android.util.Log
import com.alibaba.android.arouter.facade.template.ILogger
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.android.arouter.utils.DefaultLogger
import com.jinyang.baserouter.executor.DispatcherExecutor
import com.jinyang.baserouter.log
import com.jinyang.baserouter.utils.ApplicationUtil
import com.jinyang.baserouter.utils.LjyLogUtil
import java.util.concurrent.Executors
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

/**
 * @Author:         LiuJinYang
 * @CreateDate:     2021/12/8
 * @Description:
 */
open class BaseRouterApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        ApplicationUtil.instance.init(this)
            ApplicationUtil.instance.isLogin = true
        initRouter()
    }

    private fun initRouter() {
        if (BuildConfig.DEBUG) {
            ARouter.openLog()// 开启日志
            ARouter.openDebug()// 使用InstantRun的时候，需要打开该开关，上线之后关闭，否则有安全风险
            ARouter.printStackTrace(); // 打印日志的时候打印线程堆栈
            //使用自己的日志工具打印日志
            ARouter.setLogger(myLogger)
            // 使用自己提供的线程池
            ARouter.setExecutor(DispatcherExecutor.getCPUExecutor())

        }
        //需要在init之前配置才有效
        ARouter.init(this)
    }

    val myLogger = object : ILogger {
        private var mIsMonitorMode = false
        private var mIsShowStackTrace: Boolean = false
        override fun showLog(isShowLog: Boolean) {
            LjyLogUtil.setIsLog(isShowLog)
        }

        override fun showStackTrace(isShowStackTrace: Boolean) {
            mIsShowStackTrace = isShowStackTrace
        }

        override fun debug(tag: String?, message: String?) {
            LjyLogUtil.d("$tag --> $message")
        }

        override fun info(tag: String?, message: String?) {
            LjyLogUtil.i("$tag --> $message")
        }

        override fun warning(tag: String?, message: String?) {
            LjyLogUtil.w("$tag --> $message")
        }

        override fun error(tag: String?, message: String?) {
            LjyLogUtil.e("$tag --> $message")
        }

        override fun error(tag: String?, message: String?, e: Throwable?) {
            LjyLogUtil.e("$tag --> message=$message,e=${e?.message}")
        }

        override fun monitor(message: String?) {
            if (LjyLogUtil.isLog() && isMonitorMode) {
                val stackTraceElement = Thread.currentThread().stackTrace[3]
                LjyLogUtil.d("$defaultTag::monitor", message + DefaultLogger.getExtInfo(stackTraceElement))
            }
        }

        override fun isMonitorMode(): Boolean {
           return mIsMonitorMode
        }

        override fun getDefaultTag(): String {
            return "LJY_LOG"
        }
    }
}